<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogFlag"
      class="avue-dialog avue-dialog--top"
      width="60%"
      @close="cancel">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="发消息" name="message">
          <div>
            <div style="margin-top: 5px; height: 100%">
              <el-form ref="gridHeadLayout" :inline="true" :model="messageArgument"
                       class="demo-form-inline custom-form">
                <el-form-item>
                  <el-input
                    v-model="messageArgument.templateName"
                    size="mini"
                    placeholder="请输入模板名称">
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-select v-model="messageArgument.pushRange" size="mini" placeholder="请选择推送范围">
                    <el-option
                      v-for="item in pushMethodDict"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-select v-model="messageArgument.usersType" size="mini" placeholder="请选择用户类型">
                    <el-option
                      v-for="item in userTypeDict"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item class="top-button" style="margin-top: -1px">
                  <el-button size="mini" @click="messageSearch" icon="el-icon-search"></el-button>
                  <el-button size="mini" @click="messageEmpty" icon="el-icon-refresh-right"></el-button>
                </el-form-item>
                <el-table
                  row-key="id"
                  ref="messageTable"
                  border
                  :data="messageTableData"
                  v-loading="tableLoading"
                  @selection-change="messageSelectionChange"
                  :selection="selectedMessage"
                  tooltip-effect="dark"
                  height="48vh"
                  style="width: 100%;">
                  <el-table-column
                    type="selection"
                    :reserve-selection="true"
                    align="center"
                    :selectable="messageSelectable"
                    width="40">
                  </el-table-column>
                  <el-table-column
                    prop="templateName"
                    label="模板名称"
                    align="center">
                  </el-table-column>
                  <el-table-column
                    prop="messageType"
                    label="消息类型"
                    align="center">
                    <template slot-scope="scope">
                      {{ messageTypeList.find(demo => demo.id === scope.row.pushWays.messageType)?.name || '未知类型' }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="channelType"
                    label="通道类型"
                    align="center">
                    <template slot-scope="scope">
                      <dict-tag
                        :type="DICT_TYPE.MESSAGE_CHANNEL"
                        :value="scope.row.pushWays.channelType"
                      />
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>
              <el-pagination
                background
                :current-page="messagePage.currentPage"
                :page-sizes="[10, 20, 30, 40, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="messagePage.total"
                :page-size="messagePage.pageSize"
                :pager-count="5"
                @size-change="messageChangeSize"
                @current-change="messageCurrent"
                style="float: right; margin: 20px 0;">
              </el-pagination>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div style="float: right">
        <el-button size="small" @click="cancel">取 消</el-button>
        <el-button size="small" type="primary" @click="determine">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getPage, getByIds as getMessageByIds} from "@/api/message/template";

export default {
  data() {
    return {
      title: '动作配置',
      selectedMessage: [], // 勾选存储消息列表
      messageSelectList: [], // 已勾选消息列表
      messageSelect: [], // 控制是否能勾选发消息列表
      messageActionData: [],
      dialogFlag: false,
      tableLoading: false,
      activeName: 'second',
      messageArgument: {},
      pushMethodDict: [],
      userTypeDict: [],
      messageTableData: [],
      messagePage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      messageTypeList: [
        {id: '1', name: '文本消息'},
      ]
    };
  },
  mounted() {
    this.pushMethodDict = this.$store.state.dict.dictDatas.message_push_method
    this.userTypeDict = this.$store.state.dict.dictDatas.message_user_type
  },
  methods: {
    // 消息类型方法
    messageSelectionChange(data) {
      // 勾选发消息
      if (data.length > 0) {
        this.messageSelectList = data;
      }
    },
    messageSelectable(row) {
      if (this.messageSelect.length > 0) {
        let ids = this.messageSelect.map(item => item.id)
        return !ids.includes(row.id)
      } else {
        return true;
      }
    },
    messageChangeSize(val) {
      this.messagePage.pageSize = val
      this.messageOnLoad()
    },
    messageCurrent(val) {
      this.messagePage.currentPage = val
      this.messageOnLoad()
    },
    messageSearch() {
      this.messageOnLoad(this.messageArgument)
    },
    messageEmpty() {
      this.messageArgument = {}
      this.messageOnLoad()
    },
    messageInit() {
      this.activeName = 'message';
      this.messageOnLoad();
    },
    messageOnLoad(params = {}) {
      params.currentPage = this.messagePage.currentPage
      params.pageSize = this.messagePage.pageSize
      this.tableLoading = true
      getPage(params).then(res => {
        const data = res.data
        this.messageTableData = data.records
        this.messageTableData.forEach(item => {

          item.pushWays = JSON.parse(item.pushWays)
          item.relatedParameter = JSON.parse(item.relatedParameter)
          item.relatedParameter.templateId = item.id
          item.relatedParameter.channelType = item.pushWays.channelType
          item.relatedParameter = JSON.stringify(item.relatedParameter)
        })
        this.tableLoading = false
        this.messagePage.total = data.total
      })
    },

    handleClick(tab) {
      if (tab.name === 'message') {
        this.messageInit();
      }
    },
    init(actionData) {
      let messageData = []
      if (actionData.length > 0) {
        actionData.forEach(e => {
          if (e.actionType == 1) {
            messageData.push(e);
          }
        })
        if (messageData.length > 0) {
          this.selectedMessage = messageData;
          this.selectedMessage.forEach(item => {
            item.isAppend = true;
          });
          const ids = messageData.map(item => item.actionId).join(',');
          getMessageByIds(ids).then((res) => {
            this.messageSelect = res.data;
          })
        }
      }
      this.messageInit();
      this.dialogFlag = true;
    },
    determine() {

      this.messageSelectList.push(...this.selectedMessage);
      this.buildAndSave()
    },
    buildAndSave() {
      let actionData = [];
      this.$nextTick(async () => {
        this.messageSelectList.forEach(e => {
          if (e.isAppend) {
            actionData.push(e);
          } else {
            let data = {
              actionId: e.id,
              actionName: e.templateName,
              actionType: 1, // 1 发消息
              outputWay: e.pushWays.channelType,
              relatedParameter: e.relatedParameter,
            }
            actionData.push(data);
          }
        });
        this.$emit("saveAction", actionData)
        this.cancel()
      })
    },
    cancel() {
      this.dialogFlag = false;
      this.selectedMessage = [];
      this.messageSelectList = [];
      this.messageSelect = [];
      this.$refs.messageTable.clearSelection();
    }
  },
};
</script>

<style scoped>
</style>
